﻿using System;
using System.Drawing;
using System.Windows.Forms;

namespace CalculatorApp
{
    public partial class CalculatorForm : Form
    {
        private string currentExpression = string.Empty;

        public CalculatorForm()
        {
            InitializeComponent();
        }

        private void NumberButton_Click(object sender, EventArgs e)
        {
            Button button = (Button)sender;
            string number = button.Text;
            currentExpression += number;
            UpdateDisplay();
        }

        private void OperatorButton_Click(object sender, EventArgs e)
        {
            Button button = (Button)sender;
            string @operator = button.Text;
            currentExpression += @operator;
            UpdateDisplay();
        }

        private void EqualsButton_Click(object sender, EventArgs e)
        {
            try
            {
                double result = EvaluateExpression();
                currentExpression += "=" + result.ToString();
                UpdateDisplay();
            }
            catch (Exception ex)
            {
                MessageBox.Show("错误：" + ex.Message, "计算器", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void UndoButton_Click(object sender, EventArgs e)
        {
            if (currentExpression.Length > 0)
            {
                currentExpression = currentExpression.Substring(0, currentExpression.Length - 1);
                UpdateDisplay();
            }
        }

        private void ClearButton_Click(object sender, EventArgs e)
        {
            currentExpression = string.Empty;
            UpdateDisplay();
        }

        private double EvaluateExpression()
        {
           
            return Convert.ToDouble(new System.Data.DataTable().Compute(currentExpression, null));
        }

        
        private void UpdateDisplay()
        {
            
            DisplayRichTextBox.Clear();

            
            foreach (char c in currentExpression)
            {
                // 如果字符是一个运算符，则设置它的颜色为蓝色
                if (IsOperator(c))
                {
                    DisplayRichTextBox.SelectionColor = Color.FromArgb(87,156,249);
                }
                else
                {
                    DisplayRichTextBox.SelectionColor = Color.Black;
                }

                
                DisplayRichTextBox.AppendText(c.ToString());
            }
        }

 
        private bool IsOperator(char c)
        {
            return c == '+' || c == '-' || c == '×' || c == '÷'||c=='=';
        }




    }
}